<template>
  <div class="course-detail page-container" v-loading="loading">
    <!-- 课程基本信息 -->
    <div class="course-header blog-card">
      <div class="course-info-container">
        <div class="course-cover">
          <img :src="courseInfo.cover" :alt="courseInfo.title">
        </div>
        <div class="course-info">
          <h1 class="course-title">{{ courseInfo.title }}</h1>
          <div class="course-meta">
            <div class="meta-item">
              <i class="el-icon-user"></i>
              <span>讲师: {{ courseInfo.teacher }}</span>
            </div>
            <div class="meta-item">
              <i class="el-icon-date"></i>
              <span>更新时间: {{ courseInfo.updateTime || '2023-06-15' }}</span>
            </div>
            <div class="meta-item">
              <i class="el-icon-user"></i>
              <span>{{ courseInfo.studentCount || 0 }}人学习</span>
            </div>
            <div class="meta-item">
              <el-rate
                v-model="courseInfo.rating"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}分"
              ></el-rate>
            </div>
          </div>
          <div class="course-progress">
            <div class="progress-text">学习进度: {{ courseInfo.progress || 0 }}%</div>
            <el-progress :percentage="courseInfo.progress || 0"></el-progress>
          </div>
          <div class="course-actions">
            <el-button type="primary" @click="continueStudy">继续学习</el-button>
            <el-button type="success" @click="showMaterials">课程资料</el-button>
            <el-button @click="showComments">学生评价</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 课程内容 -->
    <div class="course-content">
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 课程介绍 -->
        <el-tab-pane label="课程介绍" name="intro">
          <div class="intro-content blog-card">
            <h3>课程简介</h3>
            <div class="course-description">
              <p>{{ courseInfo.description || '暂无课程介绍' }}</p>
            </div>
            <h3>课程目标</h3>
            <div class="course-objectives">
              <ul>
                <li v-for="(objective, index) in courseInfo.objectives" :key="index">{{ objective }}</li>
              </ul>
            </div>
            <h3>适合人群</h3>
            <div class="course-target">
              <p>{{ courseInfo.targetAudience || '本课程适合所有对该学科感兴趣的学生' }}</p>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 章节列表 -->
        <el-tab-pane label="章节目录" name="chapters">
          <div class="chapters-list">
            <el-collapse v-model="activeChapters">
              <el-collapse-item v-for="chapter in courseInfo.chapters" :key="chapter.id" :title="chapter.title" :name="chapter.id">
                <div class="section-list">
                  <div 
                    v-for="section in chapter.sections" 
                    :key="section.id" 
                    class="section-item"
                    :class="{ 'completed': section.completed }"
                    @click="watchSection(chapter.id, section.id)"
                  >
                    <div class="section-info">
                      <i class="el-icon-video-play"></i>
                      <span class="section-title">{{ section.title }}</span>
                    </div>
                    <div class="section-meta">
                      <span class="section-duration">{{ section.duration || '10:00' }}</span>
                      <i v-if="section.completed" class="el-icon-check completed-icon"></i>
                    </div>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-tab-pane>
        
        <!-- 课程评价 -->
        <el-tab-pane label="学生评价" name="comments">
          <div class="comments-section">
            <div class="comments-header">
              <div class="rating-overview">
                <div class="rating-score">
                  <span class="score">{{ courseInfo.rating || 4.5 }}</span>
                  <el-rate
                    v-model="courseInfo.rating"
                    disabled
                    show-score
                    text-color="#ff9900"
                    score-template="{value}"
                  ></el-rate>
                </div>
                <div class="rating-count">
                  共 {{ courseInfo.ratingCount || 0 }} 条评价
                </div>
              </div>
              <div class="comment-action">
                <el-button type="primary" @click="addComment">添加评价</el-button>
              </div>
            </div>
            
            <div class="comments-list">
              <div v-for="comment in comments" :key="comment.id" class="comment-item blog-card">
                <div class="comment-user">
                  <el-avatar :src="comment.avatar"></el-avatar>
                  <div class="user-info">
                    <div class="username">{{ comment.username }}</div>
                    <div class="comment-time">{{ comment.time }}</div>
                  </div>
                </div>
                <div class="comment-rating">
                  <el-rate v-model="comment.rating" disabled></el-rate>
                </div>
                <div class="comment-content">
                  {{ comment.content }}
                </div>
                <div v-if="comment.reply" class="comment-reply">
                  <div class="reply-title">讲师回复:</div>
                  <div class="reply-content">{{ comment.reply }}</div>
                </div>
              </div>
              
              <!-- 空状态 -->
              <el-empty v-if="comments.length === 0" description="暂无评价"></el-empty>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 视频播放对话框 -->
    <el-dialog
      title="课程视频"
      :visible.sync="videoDialogVisible"
      width="80%"
      :before-close="handleCloseVideo"
      class="video-dialog"
    >
      <div class="video-container">
        <div class="video-player">
          <img src="https://picsum.photos/800/450" alt="视频播放器" class="video-placeholder">
          <div class="video-controls">
            <el-button type="primary" icon="el-icon-video-play" circle></el-button>
          </div>
        </div>
        <div class="video-info">
          <h3>{{ currentSection.title }}</h3>
          <p>{{ currentSection.description || '暂无描述' }}</p>
        </div>
      </div>
    </el-dialog>

    <!-- 添加评价对话框 -->
    <el-dialog
      title="添加课程评价"
      :visible.sync="commentDialogVisible"
      width="50%"
    >
      <el-form :model="commentForm" label-width="80px">
        <el-form-item label="评分">
          <el-rate v-model="commentForm.rating" :colors="['#99A9BF', '#F7BA2A', '#FF9900']"></el-rate>
        </el-form-item>
        <el-form-item label="评价内容">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入您对课程的评价"
            v-model="commentForm.content">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="commentDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitComment">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCourseById, getCourseChapters } from '@/api/course'

export default {
  name: 'CourseDetail',
  data() {
    return {
      courseId: null,
      loading: false,
      courseInfo: {
        title: '',
        cover: '',
        teacher: '',
        description: '',
        rating: 4.5,
        progress: 30,
        objectives: [
          '掌握该课程的基本概念和原理',
          '能够独立完成相关实践练习',
          '具备解决实际问题的能力'
        ],
        targetAudience: '本课程适合所有对该学科感兴趣的学生，无需特别的前置知识。',
        chapters: []
      },
      activeTab: 'intro',
      activeChapters: ['1'],
      videoDialogVisible: false,
      commentDialogVisible: false,
      currentSection: {
        title: '',
        description: ''
      },
      commentForm: {
        rating: 5,
        content: ''
      },
      comments: [
        {
          id: 1,
          username: '张同学',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          rating: 5,
          content: '这门课程非常棒，老师讲解清晰，内容丰富，学到了很多知识，强烈推荐！',
          time: '2023-06-10',
          reply: '感谢您的支持，我们会继续努力提供更好的教学内容。'
        },
        {
          id: 2,
          username: '李同学',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          rating: 4,
          content: '课程内容很实用，但是有些地方讲解不够详细，希望能够增加一些实例讲解。',
          time: '2023-06-08',
          reply: null
        }
      ]
    }
  },
  created() {
    this.courseId = this.$route.params.id
    this.fetchCourseDetail()
    this.fetchCourseChapters()
  },
  methods: {
    fetchCourseDetail() {
      this.loading = true
      
      // 模拟请求
      setTimeout(() => {
        // 从store中获取课程列表
        const courses = this.$store.state.courses || []
        const course = courses.find(c => c.id.toString() === this.courseId) || {}
        
        this.courseInfo = {
          ...this.courseInfo,
          ...course,
          progress: Math.floor(Math.random() * 100),
          rating: 4.5,
          ratingCount: Math.floor(Math.random() * 100) + 10,
          description: '这是一门非常精彩的课程，包含丰富的教学内容和实践案例。通过本课程的学习，您将掌握该领域的核心知识和技能，为今后的学习和工作打下坚实的基础。课程内容涵盖基础理论和实践应用，通过循序渐进的讲解，帮助您全面理解相关概念和方法。'
        }
        
        this.loading = false
      }, 1000)
    },
    fetchCourseChapters() {
      // 模拟请求
      setTimeout(() => {
        this.courseInfo.chapters = [
          {
            id: '1',
            title: '第一章：基础概念',
            sections: [
              { id: '1-1', title: '1.1 课程介绍', duration: '10:30', completed: true },
              { id: '1-2', title: '1.2 基本概念讲解', duration: '15:45', completed: true },
              { id: '1-3', title: '1.3 实例分析', duration: '20:15', completed: false }
            ]
          },
          {
            id: '2',
            title: '第二章：进阶内容',
            sections: [
              { id: '2-1', title: '2.1 进阶理论', duration: '18:20', completed: false },
              { id: '2-2', title: '2.2 实践应用', duration: '22:10', completed: false },
              { id: '2-3', title: '2.3 案例分析', duration: '16:40', completed: false }
            ]
          },
          {
            id: '3',
            title: '第三章：高级技巧',
            sections: [
              { id: '3-1', title: '3.1 高级方法', duration: '25:15', completed: false },
              { id: '3-2', title: '3.2 综合实例', duration: '30:00', completed: false },
              { id: '3-3', title: '3.3 课程总结', duration: '15:30', completed: false }
            ]
          }
        ]
      }, 1000)
    },
    continueStudy() {
      // 查找第一个未完成的小节
      let targetChapter = null
      let targetSection = null
      
      for (const chapter of this.courseInfo.chapters) {
        const uncompletedSection = chapter.sections.find(section => !section.completed)
        if (uncompletedSection) {
          targetChapter = chapter
          targetSection = uncompletedSection
          break
        }
      }
      
      if (targetChapter && targetSection) {
        this.watchSection(targetChapter.id, targetSection.id)
      } else {
        // 如果全部完成，播放第一章第一节
        const firstChapter = this.courseInfo.chapters[0]
        if (firstChapter && firstChapter.sections.length > 0) {
          this.watchSection(firstChapter.id, firstChapter.sections[0].id)
        }
      }
    },
    watchSection(chapterId, sectionId) {
      // 查找对应章节和小节
      const chapter = this.courseInfo.chapters.find(c => c.id === chapterId)
      if (chapter) {
        const section = chapter.sections.find(s => s.id === sectionId)
        if (section) {
          this.currentSection = {
            ...section,
            chapterTitle: chapter.title
          }
          this.videoDialogVisible = true
        }
      }
    },
    handleCloseVideo() {
      // 模拟完成学习
      const chapterId = this.currentSection.id.split('-')[0]
      const sectionId = this.currentSection.id
      
      const chapter = this.courseInfo.chapters.find(c => c.id === chapterId)
      if (chapter) {
        const section = chapter.sections.find(s => s.id === sectionId)
        if (section) {
          section.completed = true
        }
      }
      
      // 更新学习进度
      this.updateProgress()
      
      this.videoDialogVisible = false
    },
    updateProgress() {
      // 计算总小节数和已完成小节数
      let totalSections = 0
      let completedSections = 0
      
      this.courseInfo.chapters.forEach(chapter => {
        totalSections += chapter.sections.length
        completedSections += chapter.sections.filter(s => s.completed).length
      })
      
      // 计算进度百分比
      if (totalSections > 0) {
        this.courseInfo.progress = Math.floor((completedSections / totalSections) * 100)
      }
    },
    showMaterials() {
      this.$router.push(`/materials?courseId=${this.courseId}`)
    },
    showComments() {
      this.activeTab = 'comments'
    },
    addComment() {
      this.commentDialogVisible = true
    },
    submitComment() {
      if (!this.commentForm.content) {
        this.$message.warning('请输入评价内容')
        return
      }
      
      // 添加新评价
      const newComment = {
        id: Date.now(),
        username: this.$store.state.userInfo.name || '学生用户',
        avatar: this.$store.state.userInfo.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        rating: this.commentForm.rating,
        content: this.commentForm.content,
        time: new Date().toLocaleDateString(),
        reply: null
      }
      
      this.comments.unshift(newComment)
      
      // 重新计算平均评分
      const totalRating = this.comments.reduce((sum, comment) => sum + comment.rating, 0)
      this.courseInfo.rating = (totalRating / this.comments.length).toFixed(1)
      this.courseInfo.ratingCount = this.comments.length
      
      this.$message.success('评价提交成功')
      this.commentDialogVisible = false
      
      // 重置表单
      this.commentForm = {
        rating: 5,
        content: ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.course-detail {
  padding-bottom: 40px;
}

.course-header {
  margin-bottom: 20px;
  padding: 20px;
}

.course-info-container {
  display: flex;
  
  .course-cover {
    width: 300px;
    height: 200px;
    overflow: hidden;
    border-radius: 8px;
    margin-right: 30px;
    flex-shrink: 0;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  
  .course-info {
    flex: 1;
  }
}

.course-title {
  font-size: 24px;
  margin: 0 0 15px;
  color: #303133;
}

.course-meta {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
  
  .meta-item {
    margin-right: 20px;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    color: #606266;
    
    i {
      margin-right: 5px;
    }
  }
}

.course-progress {
  margin-bottom: 20px;
  
  .progress-text {
    margin-bottom: 5px;
    color: #606266;
  }
}

.course-actions {
  .el-button {
    margin-right: 15px;
  }
}

.course-content {
  margin-bottom: 30px;
}

.intro-content {
  padding: 20px;
  
  h3 {
    font-size: 18px;
    margin: 20px 0 10px;
    color: #303133;
    
    &:first-child {
      margin-top: 0;
    }
  }
  
  .course-description {
    color: #606266;
    line-height: 1.6;
  }
  
  .course-objectives {
    ul {
      padding-left: 20px;
      
      li {
        margin-bottom: 10px;
        color: #606266;
      }
    }
  }
  
  .course-target {
    color: #606266;
    line-height: 1.6;
  }
}

.chapters-list {
  .section-list {
    padding-left: 20px;
  }
  
  .section-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #EBEEF5;
    cursor: pointer;
    
    &:last-child {
      border-bottom: none;
    }
    
    &:hover {
      background-color: #F5F7FA;
    }
    
    &.completed {
      color: #67C23A;
      
      .section-title {
        color: #67C23A;
      }
    }
  }
  
  .section-info {
    display: flex;
    align-items: center;
    
    i {
      margin-right: 10px;
    }
  }
  
  .section-meta {
    display: flex;
    align-items: center;
    
    .section-duration {
      margin-right: 10px;
      color: #909399;
    }
    
    .completed-icon {
      color: #67C23A;
    }
  }
}

.comments-section {
  padding: 20px;
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.rating-overview {
  display: flex;
  align-items: center;
  
  .rating-score {
    display: flex;
    align-items: center;
    margin-right: 20px;
    
    .score {
      font-size: 32px;
      font-weight: bold;
      color: #FF9900;
      margin-right: 10px;
    }
  }
  
  .rating-count {
    color: #909399;
  }
}

.comments-list {
  .comment-item {
    padding: 20px;
    margin-bottom: 20px;
  }
  
  .comment-user {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    
    .user-info {
      margin-left: 10px;
      
      .username {
        font-weight: bold;
        color: #303133;
      }
      
      .comment-time {
        font-size: 12px;
        color: #909399;
      }
    }
  }
  
  .comment-rating {
    margin-bottom: 10px;
  }
  
  .comment-content {
    color: #606266;
    line-height: 1.6;
    margin-bottom: 10px;
  }
  
  .comment-reply {
    background-color: #F5F7FA;
    padding: 10px;
    border-radius: 4px;
    
    .reply-title {
      font-weight: bold;
      margin-bottom: 5px;
      color: #303133;
    }
    
    .reply-content {
      color: #606266;
    }
  }
}

.video-container {
  .video-player {
    position: relative;
    margin-bottom: 20px;
    
    .video-placeholder {
      width: 100%;
      height: auto;
      border-radius: 4px;
    }
    
    .video-controls {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
  
  .video-info {
    h3 {
      font-size: 18px;
      margin: 0 0 10px;
      color: #303133;
    }
    
    p {
      color: #606266;
      line-height: 1.6;
    }
  }
}

@media (max-width: 768px) {
  .course-info-container {
    flex-direction: column;
    
    .course-cover {
      width: 100%;
      height: auto;
      margin-right: 0;
      margin-bottom: 20px;
    }
  }
  
  .comments-header {
    flex-direction: column;
    align-items: flex-start;
    
    .comment-action {
      margin-top: 15px;
    }
  }
}
</style> 